import { UserAPI } from '@/api/request/user'
import router from '@/router'
import { usePiniaStorage } from '@/hooks/pinia/usePiniaStorage'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import store from '..'

interface LoginParams {
  username: string
  password: string
}

const userStore = defineStore('user', () => {
  const token = ref('')
  usePiniaStorage({ token })

  /**
   * todo 登录方法
   * @param data
   * @returns
   */
  async function login(data: LoginParams) {
    const [err, result] = await UserAPI.login(data)
    if (!err) token.value = result.token
    return [err]
  }

  // todo 登出方法
  function logout() {
    token.value = ''
    router.push('/login')
  }

  return {
    token,
    login,
    logout,
  }
})

export const useUserStore = () => userStore(store)
